package com.meizitu;

import com.meizitu.entity.Image;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 下载图片
 *
 * @author zhouinfo
 * @Create Date 2016-07-31 15:56
 */
public class DownloadImage {

    /***
     * 下载图片
     *
     * @param imageList
     */
    public static void downloadImageList(List<Image> imageList) {
        String savePath = null;
        savePath = Main.BASICS_SAVA_PATH + imageList.get(0).getAlt();
        File sf = new File(savePath);
        if (!sf.exists()) {
            sf.mkdirs();
        }
        try {
            for (Image image : imageList) {
                if (image.getAlt() == null || "erweima.jpg".equals(image.getName())) {
                    continue;
                }
                URL url = new URL(image.getUrl());
                URLConnection con = url.openConnection();
                con.setConnectTimeout(60 * 1000);
                InputStream is = con.getInputStream();
                OutputStream os = new FileOutputStream(new File(savePath + "\\" + image.getName()));
                byte[] buf = new byte[4096];
                int length = 0;
                System.out.println("开始下载: " + image.getUrl());
                while ((length = is.read(buf, 0, buf.length)) != -1) {
                    os.write(buf, 0, length);
                }
                is.close();
                os.close();
                System.out.println("下载完成: " + savePath + "\\" + image.getName());
            }
        } catch (Exception e) {
            System.out.println("下载失败! " + e.toString());
        }
    }
}
